package com.link.base.base.workplan.controller;

import com.link.base.base.workplan.model.Workplan;
import com.link.base.base.workplan.service.WorkplanService;
import com.link.base.basic.model.ListOfValue;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.LovUtil;
import com.link.core.cllog.LCLogger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author unknown
 * @date unknown
 * @comments 任务计划
 */
@Controller
@RequestMapping("/link/workplan")
public class WorkplanController extends BasicController<Workplan> {
    @Resource
    private WorkplanService workplanService;

    @Override
    public BasicService<Workplan> getBasicService() {
        return workplanService;
    }

    @RequestMapping(value = "/queryWorkplanPage")
    @ResponseBody
    public Map<String, Object> queryOptyList(@JsonParam Workplan record,@JsonParam  QueryParams qps, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryWorkplanPage")
                .withMessage("查询工作计划列表信息...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            qps.invokePreFilterAndSorter();
            //处理"周期间"过滤逻辑
            List<Filter> filterList = qps.getFilterByProperty("begin_time");
            List<Filter> yearList = qps.getFilterByProperty("year");
            List<Filter> periodTypeList = qps.getFilterByProperty("periodType");
            if (filterList.size() > 0 && yearList.size() > 0 && periodTypeList.size() > 0) {
                String weekLovName = LovUtil.getLovName("WORKPLAN_CYCLE_TYPE", "WEEK");
                //选中"周计划"下查询周期间有效
                if (periodTypeList.get(0).getValue().equals(weekLovName)) {
                    for (int i = 0; i < filterList.size(); i++) {
                        Filter filter = filterList.get(i);
                        String weekPeriod = filter.getValue();
                        String[] beginDts = weekPeriod.split(" ~ ");
                        //keyFilter选中年份
                        String year = yearList.get(0).getValue();
                        //起始时间
                        String sDateTo = year + "-" + beginDts[0];
                        //截至时间
                        String sDateFrom = year + "-" + beginDts[1];
                        //移除原begin_time的Filter
                        qps.removeFilter(filter);
                        // >= 起始时间
                        Filter filterStart = new Filter("begin_time", Filter.OP_GREAT_EQUAL, sDateTo);
                        // < 结束时间
                        Filter filterEnd = new Filter("begin_time", Filter.OP_LESS_THEN, sDateFrom);
                        qps.addFilter(filterStart);
                        qps.addFilter(filterEnd);
                    }
                } else {
                    for (int i = 0; i < filterList.size(); i++) {
                        Filter filter = filterList.get(i);
                        qps.removeFilter(filter);
                    }
                }
            }


            return this.queryByExamplePage(qps, record, session, request, response);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Workplan>());
            result.put("message", e.toString());
        }
        return result;
    }

    /**
     * 工作计划导出
     * @author     unknown
     * @param       entity
     * @return
     * @exception
     * @update  yipeng.zhu@hand-china.com
     * @date        2019/2/28 11:29
     * @version     1.0
     */
    @Override
    @RequestMapping(value = "/queryWorkplanPage/exportData")
    @ResponseBody
    public Map<String, Object> exportData(Workplan entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryWorkplanPage/exportData")
                .withMessage("导出列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            String exportType = "xlsx";
            String exportFileType = qps.getExportFileType();
            ExportWriter exportWriter;
            if (exportType.equals(exportFileType)) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }
            Workplan t = (Workplan) BasicModel.transformClass(entity.getClass(), qps);
            List<Workplan> list = getBasicService().queryByExamplePage(t);
            while (!qps.getStopExport()) {
                exportWriter.wirteData(list);
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/listWeekPeriod/{yearMonth}")
    @ResponseBody
    public Object listWeekPeriod(@PathVariable String yearMonth, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("listWeekPeriod")
                .withMessage("查询当前年月下各周期间...").flush();
        ArrayList<Object> list = new ArrayList<Object>();
        try {
            String noSelectMatch = "noSelectMatch";
            if (yearMonth != noSelectMatch) {
                String str = "&";
                if (yearMonth.contains(str)) {
                    String[] arrYearMonth = yearMonth.split("&");
                    int year = Integer.parseInt(arrYearMonth[0]);
                    String intMonth = arrYearMonth[1].substring(0, arrYearMonth[1].length() - 1);
                    //GregorianCalendar月份从0开始
                    int month = Integer.parseInt(intMonth) - 1;
                    Calendar dtFrom = new GregorianCalendar();
                    Calendar calendar = new GregorianCalendar(year, month, 1);
                    int DD = calendar.get(Calendar.DAY_OF_WEEK);
                    calendar.add(Calendar.DATE, 2 - DD);
                    dtFrom = (Calendar) calendar.clone();
                    calendar.add(Calendar.DATE, 7);
                    Calendar dtTo = new GregorianCalendar();
                    dtTo = (Calendar) calendar.clone();
                    while (dtFrom.get(Calendar.MONTH) == month || dtTo.get(Calendar.MONTH) == month) {
                        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
                        String sDtFrom = sdf.format(dtFrom.getTime());
                        String sDtTo = sdf.format(dtTo.getTime());
                        String dtString = sDtFrom + " ~ " + sDtTo;
                        ListOfValue record = new ListOfValue();
                        record.setName(dtString);
                        list.add(record);
                        dtFrom = (Calendar) dtTo.clone();
                        calendar.add(Calendar.DATE, 7);
                        dtTo = (Calendar) calendar.clone();
                    }
                }
            }

        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return list;
    }


    /**
     * 获取年份
     */
    @RequestMapping(value = "/list/{type}")
    @ResponseBody
    public Object list(@PathVariable String type, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        QueryParams qps = new QueryParams();
        qps.addFilter(new Filter("type", type.toUpperCase()));
        List<ListOfValue> list = new ArrayList<ListOfValue>();
        try {
            Calendar clNow = new GregorianCalendar();
            int thisYear = clNow.get(Calendar.YEAR);
            int two = 2;
            for (int i = thisYear - 1; i < thisYear + two; i++) {
                ListOfValue record = new ListOfValue();
                String currenYear = String.valueOf(i);
                record.setType(type);
                record.setName(currenYear);
                record.setVal(currenYear);
                list.add(record);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return list;
    }

    /**
     * 查看任务列表
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "getPlanListPage")
    @ResponseBody
    public Map<String, Object> getPlanList(Workplan entity) {
        Map<String, Object> result = new HashMap<>();
        if (entity.getBegin_time() == null || "".equals(entity.getBegin_time())) {
            entity.setBegin_time(null);
        }
        if (entity.getEnd_time() == null || "".equals(entity.getEnd_time())) {
            entity.setEnd_time(null);
        }
        List<Workplan> list = workplanService.getPlanList(entity);
        result.put("success", true);
        result.put("rows", list);
        result.put("total", list.size());
        return result;

    }

    /**
     * 根据月份查询当月的所有任务
     */
    @RequestMapping(value = "/queryAllByMonth")
    @ResponseBody
    public Map<String, Object> queryAllByMonth(Workplan entity, HttpSession session, HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String inputDateStr = entity.getFilterParm2();
            Map<String, Workplan> allTasks = workplanService.queryAllByMonth(entity);
            result.put("result", allTasks);
            // 查询默认日期的任务列表,清空字段,避免影响查询
            entity.setBegin_time(null);
            entity.setFilterParm1("yyyy-MM-dd");
            entity.setFilterParm2(inputDateStr);
            List<Workplan> currentDateTask = workplanService.queryByExamplePage(entity);
            // 根据每天获取当日任务
            result.put("currentDateTask", currentDateTask);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
}
